<template>
  <div class="login-container">
    <loginHeaderVue></loginHeaderVue>
    <div class="login-box">
      <el-form
        ref="loginForm"
        :model="loginData"
        :rules="loginRules"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >
        <div class="title">欢迎登录小兔仙管理系统</div>

        <el-form-item prop="username">
          <el-input
            ref="username"
            v-model="loginData.username"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
            prefix-icon="el-icon-user"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginData.password"
            name="password"
            tabindex="2"
            auto-complete="on"
            prefix-icon="el-icon-lock"
            type="password"
          />
        </el-form-item>

        <el-form-item label="" prop="captcha">
          <el-row>
            <el-col :span="16">
              <el-input
                v-model="loginData.captcha"
                prefix-icon="el-icon-circle-check"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <img
                src="http://127.0.0.1:7001/imagecode"
                style="width: 145px; height: 47px; margin-left: 28px"
                ref="imageCaptcha"
                @click="updateCaptcha"
                :key="1"
              />
            </el-col>
          </el-row>
        </el-form-item>

        <el-button
          class="loginBtn"
          type="primary"
          style="width: 100%; margin-bottom: 30px"
          @click="loginBtn"
          >登录</el-button
        >
        <ul class="auth_box">
          <li class="iconfont icon-weixin" style="color:#00C800"></li>
          <li class="iconfont icon-QQ" style="color:deepskyblue"></li>
          <li class="iconfont icon-GitHub">
            <a href="http://127.0.0.1:7001/passport/github"></a>
          </li>
          <li class="iconfont icon-weibo" style="color:#E71F19"></li>
        </ul>
        <!-- <router-link to="/register" class="register"
          >还没有账号？立即注册</router-link
        > -->
        <a class="register" @click="goRegister">还没有账号？立即注册</a>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { loginUser } from "@/api";
const Cookies = require("js-cookie");
// import Cookies from 'js-cookie'
import { Component, Vue, Ref } from "vue-property-decorator";
import loginHeaderVue from "./components/login-header.vue";

@Component({
  name: "Login",
  components: {
    loginHeaderVue,
  },
})
export default class Login extends Vue {
  loginData = {
    username: "xiaotuxian005",
    email: "",
    phone: "",
    password: "com.123456",
    captcha: "",
    type: "normal", // 默认类型是 normal
  };
  private validateName = (rule: any, value: string, callback: any) => {
    const normalReg = /^[A-Za-z0-9]{6,}$/;
    const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    const phoneReg = /^1[3456789]\d{9}$/;
    if (!value) {
      callback(new Error("请输入用户名"));
    } else if (emailReg.test(value)) {
      // 如果是邮箱登录
      this.loginData.email = this.loginData.username;
      this.loginData.type = "email";
      callback();
    } else if (phoneReg.test(value)) {
      // 如果是手机登录
      this.loginData.phone = this.loginData.username;
      this.loginData.type = "phone";
      callback();
    } else if (normalReg.test(value)) {
      // 普通登录直接放行
      this.loginData.type = "normal";
      callback();
    }
  };
  private validatePwd = (rule: any, value: string, callback: any) => {
    const reg =
      /^(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)(?=.*[,\.#%'\+\*\-:;^_`].*))[,\.#%'\+\*\-:;^_`0-9A-Za-z]{8,}$/;
    if (!value) {
      callback(new Error("请输入密码"));
    } else if (value.length < 8) {
      callback(new Error("密码至少是8位"));
    } else if (!reg.test(value)) {
      callback(new Error("密码必须是数字字母符号组合"));
    } else {
      callback();
    }
  };
  private validateCapt = (rule: any, value: string, callback: any) => {
    const reg = /^[A-Za-z0-9]{4}$/;
    if (!value) {
      callback(new Error("请输入验证码"));
    } else if (value.length < 4) {
      callback(new Error("验证码至少是4位"));
    } else if (!reg.test(value)) {
      callback(new Error("验证码必须是数字或字母组成"));
    } else {
      callback();
    }
  };
  // 校验规则
  loginRules = {
    username: [{ validator: this.validateName, trigger: "blur" }],
    password: [{ validator: this.validatePwd, trigger: "blur" }],
    captcha: [{ validator: this.validateCapt, trigger: "blur" }],
  };
  // 点击更改验证码
  @Ref() readonly imageCaptcha!: HTMLImageElement;
  private updateCaptcha() {
    // (this.imageCaptcha as any).src
    this.imageCaptcha.src = `http://127.0.0.1:7001/imagecode?r=${Math.random()}`;
  }
  private goRegister(){
    // this.updateCaptcha()
    this.$router.push('/register')
  }
  // 登录
  @Ref() readonly loginForm!: HTMLFormElement;
  private loginBtn() {
    this.loginForm.validate((valid: boolean) => {
      if (valid) {
        loginUser(this.loginData)
          .then((response: any) => {
            console.log(response);
            if (response.status === 200) {
              // (this as any).$store.commit('user/setUserInfo',response.data.data)
              // localStorage.setItem('id',response.data.data.id);
              sessionStorage.setItem('userInfo',JSON.stringify(response.data.data));
              /*
              cookie: 如果存储的内容体积不大
              sessionStorage: 如果不需要持久化存储
              localStorage: 如果体积较大, 又需要持久化存储
              * */
              // sessionStorage.setItem("token", data.data.token); 后端帮我们保存了token到cookies中
              (this as any).$message.success("登录成功,小兔仙管理系统欢迎您");
              this.$router.push("/home");
            } else {
              if (response.data.msg === "验证码不正确") {
                (this as any).$message.error(response.data.msg);
                this.updateCaptcha();
              } else {
                (this.loginData.email = ""),
                  (this.loginData.phone = ""),
                  (this.loginData.username = ""),
                  (this.loginData.password = ""),
                  (this.loginData.captcha = ""),
                  (this.loginData.type = "nomal");
              }
            }
          })
          .catch((e) => {
            this.updateCaptcha();
            (this as any).$message.error(e.response.data.msg);
          });
      } else {
        this.updateCaptcha();
        (this as any).$message.error("数据格式不对");
      }
    });
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

@supports (-webkit-mask: none) and (not (cater-color: #fff)) {
  .login-container .el-input input {
    color: #fff;
  }
}

/* reset element-ui css */
.login-container {
  .login-box {
    width: 600px;
    height: 400px;
    // background: #fff;
    border-radius: 10px;
    position: absolute;
    right: 0;
    top: 50%;
    transform: translate(-10%, -50%);
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      // padding: 12px 5px 12px 15px;
      color: black;
      height: 47px;
      caret-color: #fff;

      // 修复浏览器历史填充记录的背景颜色样式
      &:-webkit-autofill {
        transition-delay: 99999s;
        transition: color 1s ease-out, background-color 99999s;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(255, 255, 255, 0.7);
    border-radius: 5px;
    color: #454545;
  }
  .el-form-item__error {
    color: #f56c6c;
    font-size: 16px;
  }
  .loginBtn {
    background: #407ffe;
    height: 64px;
    line-height: 32px;
    font-size: 24px;
  }
  .el-col {
    height: 47px;
  }
  .el-button{
    margin-bottom: 10px !important;
  }
}
</style>

<style lang="scss" scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background: url("../assets/common/login-bg.png") no-repeat center;
  background-size: initial;
  .login-form {
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    width: 520px;
    min-height: 400px;
    padding: 35px 35px 15px;
    margin: -260px auto 0;
    .register {
      display: block;
      font-size: 18px;
      color: #407ffe;
      text-align: center;
      margin-bottom: 10px;
      text-decoration: none;
    }
    .auth_box{
      list-style: none;
      padding: 0;
      display: flex;
      justify-content: space-around;
      li{
        font-size: 30px;
        position: relative;
        a{
          display: block;
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
        }
      }
    }
  }
  .tips {
    font-size: 16px;
    color: #fff;
    text-align: center;
    margin-bottom: 10px;
    span {
      cursor: pointer;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #889aa4;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title {
    font-size: 26px;
    font-weight: 400;
    color: #eee;
    margin: 0 auto 40px;
    text-align: center;
    font-weight: 700;
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #889aa4;
    cursor: pointer;
    user-select: none;
  }
}
</style>

